# coding:utf-8
import os
import os.path as path
import time
from multiprocessing import Process
import codecs
import mistune
import pygments
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html


def get_blog_dict():
    """
    获取全部博客列表
    通过枚举目录的方式实现. 
    :return: 包含所有博客信息的列表
    """
    base_dir = "./blog_content"
    # base_dir = "/app/blog_content"

    # 构造一个键值对. key 为博客名(不包含路径, 不包含扩展名), value 为 文件全路径
    blogs = {}
    for root, dirs, files in os.walk(base_dir):
        for name in files:
            file_name, ext = path.splitext(name)
            if ext != ".md":
                continue
            blogs[file_name] = root + "/" + name
    return blogs


def get_blog_content(blog_name):
    """
    获取博客正文
    :param blog_name: 博客名字(唯一)
    :return: 博客信息构成的字典.
    """
    blogs = get_blog_dict()
    if blog_name not in blogs:
        return None
    blog_path = blogs[blog_name]
    with codecs.open(blog_path, mode='r', encoding="utf-8") as f:
        blog_md = f.read()
    blog_html = convert(blog_md)
    return blog_html


##########################################
# 以下代码用于格式转换
##########################################

class HighlightRender(mistune.Renderer):
    def block_code(self, code, lang=None):
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                   mistune.escape(code)
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter()
        return pygments.highlight(code, lexer, formatter)


def convert(blog_md):
    """
    将 markdown 转换为 html
    :param markdown_path: 输入 markdown 字符串
    :return: 返回转换完毕的 html 字符串
    """
    # 加载 css 文件
    with codecs.open('./static/css/friendly.css', mode='r', encoding='utf-8') as css_file:
        css_text = css_file.read()

    markdown = mistune.Markdown(renderer=HighlightRender())
    blog_html = markdown(blog_md)
    return css_text + blog_html


##########################################
# 以下代码用于数据更新
##########################################
def git_pull():
    os.system("cd ./blog_content")
    while True:
        os.system("git pull")
        time.sleep(300)

def update():
    p = Process(target=git_pull)
    p.start()
